package com.dr.common.ution;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import com.dr.common.pojo.*;
import com.dr.pojo.WeChatUserInfo;


/**
 * 微信操作工具类
 * @author tugou
 *
 */
public class WeChatUtil {
	
	/**
	 * 页面授权，获取微信Openid
	 * @param code
	 * @return
	 */
	public static WeChatOpenid getWeChatOpenid(String code){
		String url = WeChatFinalValue.ACCESS_OPENID_URL;
		url = url.replaceAll("APPID", WeChatContent.getInstance().getAppId());
		url = url.replaceAll("SECRET", WeChatContent.getInstance().getAppSecurt());
		url = url.replaceAll("CODE", code);
		String result = HttpClientUtil.doGet(url);
		Boolean isSuccess = checkRequestSucc(result);
		WeChatOpenid content;
		if(isSuccess){
			
			content = JsonUtil.toObject(result, WeChatOpenid.class);
		}else
		{
			RepMess mess = JsonUtil.toObject(result, RepMess.class);
			content = new WeChatOpenid();
			content.setMess(mess);
		}
		return content;
	}

	/**
	 * 下载微信临时图片工具
	 * @param mediaId
	 */
	public static Boolean weChatFileUpLoad(String mediaId,String fileName) {
		String url = WeChatFinalValue.FILE_DOWNLOAD_URL;
		url = url.replace("ACCESS_TOKEN",WeChatContent.getInstance().getAccessToken().getAccess_token());
		url = url.replace("MEDIA_ID",mediaId);
		try {
			download(url,fileName, FileFinalValue.PICTUREPATH);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static void download(String urlString, String filename,String savePath) throws Exception {
		System.out.println("开始图片下载");
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		//设置请求超时为5s
		con.setConnectTimeout(5*1000);
		// 输入流
		InputStream is = con.getInputStream();

		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		File sf=new File(savePath);
		if(!sf.exists()){
			sf.mkdirs();
		}
		File file = new File(sf.getPath()+FileFinalValue.SPLITSYMBOL+filename);
		if(file.exists()){
			file.delete();
		}
		OutputStream os = new FileOutputStream(sf.getPath()+FileFinalValue.SPLITSYMBOL+filename);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
		System.out.println("完成开始图片下载");
	}

	/**
	 * 根据OpenId抓去威信用户信息
	 * @return
	 */
	public static WeChatUserInfo getWeChatUserInfoByOpenId(WeChatOpenid content){
		String url = WeChatFinalValue.GET_USER_INFO;
		url = url.replace("ACCESS_TOKEN",content.getAccess_token());
		url = url.replace("OPENID",content.getOpenid());
		String result = HttpClientUtil.doGet(url);
		WeChatUserInfo info = JsonUtil.toObject(result,WeChatUserInfo.class);
		return info;
	}


	/**
	 * 检查请求是否成功
	 * @param content
	 * @return
	 */
	public static Boolean checkRequestSucc(String content) {
		Map<String, Object> map = JsonUtil.toObject(content, Map.class);
		if(!map.containsKey("errcode"))
			return true;		
		Double errcode = (Double) map.get("errcode");
		if(errcode == 0)
			return true;
		return false;
	}
	
	/**
	 * 获取请求返回值
	 * @param content
	 * @return
	 */
	public static Integer getRequestCode(String content){
		Map<String, String> map = JsonUtil.toObject(content, Map.class);
		if(map.containsKey("errcode"))
			return Integer.valueOf(map.get("errcode"));
		return -1;
	}
	
	/**
	 * 获取请求返回消息
	 * @param content
	 * @return
	 */
	public static String getRequestMsg(String content) {
		Map<String, String> map =JsonUtil.toObject(content, Map.class);
		if(map.containsKey("errcode"))
			return map.get("errmsg").toString();
		return null;
	}
}
